import requests
import json
from urllib import parse


def baidu_translate(word):
    # 百度翻译API的基本URL (通过分析网页请求找到的真实API地址)
    url = "https://fanyi.baidu.com/sug"

    # 设置请求头，模拟浏览器访问
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Origin': 'https://fanyi.baidu.com',
        'Referer': 'https://fanyi.baidu.com/'
    }

    # 构造表单数据
    data = {
        'kw': word
    }

    try:
        # 发送POST请求
        response = requests.post(url, headers=headers, data=data)
        response.encoding = 'utf-8'

        if response.status_code == 200:
            # 解析JSON响应
            result = response.json()

            if result.get('errno') == 0:
                # 提取翻译结果
                translations = [item['v'] for item in result['data']]
                return translations
            else:
                return ["翻译失败，API返回错误"]
        else:
            return [f"请求失败，状态码: {response.status_code}"]

    except Exception as e:
        return [f"请求过程中发生错误: {str(e)}"]


def main():
    print("百度翻译查询工具")
    print("输入'quit'或'q'退出程序")

    while True:
        # 获取用户输入
        word = input("\n请输入要翻译的单词: ").strip()

        # 检查退出条件
        if word.lower() in ('quit', 'q'):
            print("感谢使用，再见！")
            break

        if not word:
            print("输入不能为空，请重新输入")
            continue

        # 获取翻译结果
        translations = baidu_translate(word)

        # 显示结果
        print("\n翻译结果:")
        for i, trans in enumerate(translations, 1):
            print(f"{i}. {trans}")


if __name__ == '__main__':
    main()